<?php
require_once('../../../config.php');
require_once('../lib.php');
require_once('lib.php');

if (!function_exists('json_encode')) {
	ini_set('include_path', $CFG->libdir.'/pear'.PATH_SEPARATOR.ini_get('include_path'));
	require_once('HTML/AJAX/JSON.php');
}

$id      = required_param('id', PARAM_INT);
$action  = required_param('action', PARAM_CLEAN);
$groupid = optional_param('groupid', 0, PARAM_INT);  // only for teachers
$message = optional_param('message', '', PARAM_CLEAN);
$refresh = optional_param('refresh', '', PARAM_RAW); // force refresh
$last    = optional_param('last', 0, PARAM_INT);     // last time refresh or sending
$newonly = optional_param('newonly', 0, PARAM_BOOL); // show only new messages
$pname = optional_param('pname', '', PARAM_CLEAN); // by john to get to




if (!$chat = get_record('chat', 'id', $id)) {
	error('Could not find that chat room!');
}

if (!$course = get_record('course', 'id', $chat->course)) {
	error('Could not find the course this belongs to!');
}

if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
	error('Course Module ID was incorrect');
}

$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_login($course->id, false, $cm);
require_capability('mod/chat:chat',$context);

/// Check to see if groups are being used here
if ($groupmode = groups_get_activity_groupmode($cm)) {   // Groups are being used
	if ($groupid = groups_get_activity_group($cm)) {
		if (!$group = groups_get_group($groupid, false)) {
			error("That group (id $groupid) doesn't exist!");
		}
		$groupname = ': '.$group->name;
	} else {
		$groupname = ': '.get_string('allparticipants');
	}
} else {
	$groupid = 0;
	$groupname = '';
}

if (!$chat_sid = chat_login_user($chat->id, 'basic', $groupid, $course)) {
	error('Could not log in to chat room!!');
}
set_field('chat_users', 'lastping', time(), 'sid', $chat_sid);


switch ($action){
	case "exit": //user exit the chat room
		delete_records_select('chat_users', "chatid='$chat->id' AND userid='$USER->id' AND groupid='$groupid'");
		$message = new object();
		$message->chatid    = $chat->id;
		$message->userid    = $USER->id;
		$message->groupid   = $groupid;
		$message->message   = 'exit';
		$message->system    = 1;
		$message->timestamp = time();
		if (!insert_record('chat_messages', $message)) {
			error('Could not insert a chat message!');
		}
		$SESSION->chatprefs[$chat->id]='';
		unset($SESSION->chatprefs[$chat->id]);
		echo "ok";
		break;

	case "participantslist":
		if (!$participants = chat_get_users($chat->id, $groupid, $cm->groupingid)) {
			print_error('errornousers', 'chat');
		} else {
			echo "<option value='all'>".get_string("all","chat")."</option>";
			foreach($participants as $participant) {
				if ($participant->id == $USER->id) {
					continue;
				}
				$fullname=fullname($participant);
				echo "<option value='{$participant->id}'>$fullname</option>";
			}
		}
		break;

	case "participants":
		if (!$participants = chat_get_users($chat->id, $groupid, $cm->groupingid)) {
			print_error('errornousers', 'chat');
		} else {
			foreach($participants as $participant) {
				echo '<li>';
				print_user_picture($participant->id, $course->id, $participant->picture, 24, false, false, '', false);
				echo '<div class="userinfo">';
				echo fullname($participant).' ';
				if ($idle = time() - $participant->lastmessageping) {
					echo '<span class="idle">'.get_string('idle','chat').' '.format_time($idle).'</span>';
				} else {
					echo '<span class="idle" />';
				}
				echo '</div>';
				echo '</li>';
			}
		}
		break;

	case "message":
		if ($pname != "all") {
			
			$message = '/to '.$pname.' '.$message;
			
			//$message ='<span class="frommess '.$pnameT.' id="'.$pnameT.'">'.get_string("to","chat").' '.$pname.': '.$message.'</span>';
		}

		if (!empty($refresh) and data_submitted()) {
			$refreshedmessage = $message;
			chat_delete_old_users();

		} else if (empty($refresh) and data_submitted() and confirm_sesskey()) {

			if ($message!='') {
				$newmessage = new object();
				$newmessage->chatid = $chat->id;
				$newmessage->userid = $USER->id;
				$newmessage->groupid = $groupid;
				$newmessage->system = 0;
				$newmessage->message = $message;
				$newmessage->timestamp = time();
				if (!insert_record('chat_messages', $newmessage)) {
					error('Could not insert a chat message!');
				}

				set_field('chat_users', 'lastmessageping', time(), 'sid', $chat_sid);

				add_to_log($course->id, 'chat', 'talk', "view.php?id=$cm->id", $chat->id, $cm->id);
			}
			chat_delete_old_users();
		}
		echo "ok";
		break;

	case "init":
		$groupselect = $groupid ? "AND groupid=$groupid" : "";
		if($chatentered = $SESSION->chatprefs[$chat->id]['chatentered']){
			$chatentered=time();
		}
		$timemsg=$chatentered - ($CFG->initial_msgs_time_show * 60);
		$messages = get_records_select("chat_messages",
                        "chatid = $chat->id AND system = 0 $groupselect AND timestamp > $timemsg",
                        "timestamp, id" ,'*',0,$CFG->initial_msgs_num_show);
		if ($messages){
			foreach ($messages as $message) {
				$format_message = chat_format_message($message, $course->id, $USER);
				echo "<div>{$format_message->html}</div>";
			}
		} else {
			echo "<table id='1'><tr><td></td></tr></table>";
		}
		$lastmsg=chat_get_latest_message($chat->id,$groupid);
		$SESSION->chatprefs[$chat->id]['lastmsgid']= $lastmsg->id;
	break;

	case "refresh": //refresh messages
		$lastmsgid = $SESSION->chatprefs[$chat->id]['lastmsgid'];
		$chatentered = $SESSION->chatprefs[$chat->id]['chatentered'];

		$lastmsgidsql = $lastmsgid ? "AND id > $lastmsgid" : "";
		$lastsql = $newonly ? "AND timestamp > $last" : "AND timestamp > $chatentered";
		$groupselect = $groupid ? "AND groupid=$groupid" : "";

		$messages = get_records_select("chat_messages",
                        "chatid = $chat->id $lastmsgidsql $lastsql $groupselect","timestamp , id ");

		$allmessages = array();
		if ($messages){
			foreach ($messages as $message) {
				$allmessages[] = chat_format_message_ajax($message, $course->id, $USER);
			}
		}else{
			$allmessages[] = no_message();
		}
		$lastmsg=chat_get_latest_message($chat->id,$groupid);
		$SESSION->chatprefs[$chat->id]['lastmsgid']= $lastmsg->id;
		$json_messages = json_encode($allmessages);
		echo "$json_messages";
		break;

	default:
		print_error('invalidaction', 'chat');
		break;
}